package com.sojson.config.response;

import java.io.IOException;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.sojson.util.filter.FilterUtil;
import com.sojson.util.servlet.ServletUtil;

/**
 * 自定义@ResponseBody注解返回内容
 * 
 * @author liu
 * @date 2020-10-06
 */
@ControllerAdvice
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 是否对返回内容做操作,如果返回false就返回Controller返回的内容,如果返回true就执行beforeBodyWrite()方法
     * @param returnType Controller的方法信息
     */
    @SuppressWarnings("rawtypes")
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return isChangeResu();
    }

    /**
     * 在@ResponseBody输出之前做的操作,supports()返回true才会执行
     */
    @SuppressWarnings("rawtypes")
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
        Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return FilterUtil.BEFORE_BODY_WRITE.BeforeBodyWrite(body);
    }

    /**
     * 判断是否要修改结果
     * 
     * @return
     * @throws IOException
     */
    private boolean isChangeResu() {
        return ServletUtil.isChangeResu();
    }

}